// ignore_for_file: file_names, slash_for_doc_comments, must_call_super, unnecessary_overrides, override_on_non_overriding_member, must_be_immutable, prefer_const_constructors, sized_box_for_whitespace, avoid_unnecessary_containers, avoid_print

import 'package:desktop_webview_window/desktop_webview_window.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:webview_window_example/pages/appin/AppInTranslatePage.dart';
import 'package:webview_window_example/pages/englishChinese/EnglishChinesePage.dart';
import 'package:webview_window_example/utils/CommonUtils.dart';
import 'package:webview_window_example/entity/TranslateEntity.dart';

import 'dart:async';
import 'dart:io';

import 'package:mybase/base/tool/empty/FFEmpty.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';

import 'package:flutter_test/flutter_test.dart';
import 'dart:convert';

extension EnglishChinesePageStateEvent on EnglishChinesePageState {
  ///开始
  void onStart() async {
    if (FFEmpty.stringIsEmpty(textController.text)) {
      SmartDialog.showToast("待翻译的值不能为空啊");
      return;
    }

    webview = await WebviewWindow.create(
      configuration: CreateConfiguration(
          userDataFolderWindows: await _getWebViewPath(),
          titleBarTopPadding: Platform.isMacOS ? 20 : 0,
          windowWidth: 600,
          windowHeight: 600),
      iWebview: this,
    );

    TranslateEntity entity = entitys[selectIndex];

    webview
      ..setBrightness(Brightness.dark)
      ..launch(getUrl(entity.urlCode, Uri.encodeFull(textController.text)))
      ..addOnUrlRequestCallback((url) {
        debugPrint('snjj addOnUrlRequestCallback = $url');
      })
      ..addOnWebMessageReceivedCallback((message) {
        print("snjj addOnWebMessageReceivedCallback = $message");
      })
      ..onClose.whenComplete(() {
        debugPrint("snjj whenComplete");
      });
  }

  onNext() {
    selectIndex++;
    if (selectIndex >= entitys.length) {
      selectIndex = 0;
    }
    setState(() {});
  }

  Future<String> _getWebViewPath() async {
    final document = await getApplicationDocumentsDirectory();
    String path = p.join(
      document.path,
      'desktop_webview_window',
    );
    print("path = $path");
    return path;
  }

  //提取翻译文字
  extractTranslate() async {
    String? value;
    try {
      String js = """
function ycss() {
    var str = "";
    var array = document.getElementsByClassName('ryNqvb');
    for (let index = 0; index < array.length; index++) {
        const element = array[index];
        str =  str + element.innerHTML;
     }
    return str;
 }

ycss();
      """;

      value = await webview.evaluateJavaScript(js);
    } catch (e) {
      debugPrint('evaluateJavaScript error: $e');
    }

    if (FFEmpty.stringIsEmpty(value)) {
      // didFinished(0);
      SmartDialog.showToast("出现问题，请注意",
          displayTime: Duration(milliseconds: 1000));
      return;
    }

    //校验一下对错
    if (checkTranslate(value!) == false) {
      SmartDialog.showToast("待翻译的英文格式不对",
          displayTime: Duration(milliseconds: 1000));
      webview.close();
      return;
    }

    resultController.text = value!;
    webview.close();
  }

  //校验翻译的合法性
  bool checkTranslate(String text) {
    return true;
    bool ok = false;
    try {
      Map<String, dynamic> md5Map = json.decode(text);
      ok = true;
    } catch (e) {
      print("解析出错了");
    }

    return ok;
  }
}
